package com.aiyige.page.selectregion;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.aiyige.R;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventPickRegion;
import com.aiyige.base.eventbus.EventSelectRegion;
import com.aiyige.location.LocationService;
import com.aiyige.location.LocationUtil;
import com.aiyige.location.model.LocationData;
import com.aiyige.location.model.RegionData;
import com.aiyige.model.response.HotCityResponse;
import com.aiyige.model.tag.TagPopular;
import com.aiyige.page.selectregion.adapter.SelectRegionAdapter;
import com.aiyige.page.selectregion.adapter.SelectRegionHeaderAdapter;
import com.aiyige.page.selectregion.model.HeaderRegionItem;
import com.aiyige.page.selectregion.model.RegionItem;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gjiazhe.wavesidebar.WaveSideBar;
import com.oushangfeng.pinnedsectionitemdecoration.PinnedHeaderItemDecoration;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class ChinaRegionPage extends Fragment {
    public static final String TAG = ChinaRegionPage.class.getSimpleName();

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    Unbinder unbinder;
    SelectRegionHeaderAdapter currentRegionHeaderAdapter;
    SelectRegionHeaderAdapter historyRegionHeaderAdapter;
    SelectRegionHeaderAdapter hotRegionHeaderAdapter;
    View currentRegionHeader;
    View historyRegionHeader;
    View hotRegionHeader;
    SelectRegionAdapter selectRegionAdapter;
    List<RegionItem> regionItemList;
    List<HeaderRegionItem> currentRegionItemList = new LinkedList<>();
    List<HeaderRegionItem> historyRegionItemList = new LinkedList<>();
    List<HeaderRegionItem> hotRegionItemList = new LinkedList<>();
    @BindView(R.id.side_bar)
    WaveSideBar sideBar;
    Map<String, Integer> tagPositionMap = new HashMap<>();
    String[] selectionRegionTagArray;
    BroadcastReceiver receiver;

    public ChinaRegionPage() {

    }


    public static ChinaRegionPage newInstance() {
        ChinaRegionPage fragment = new ChinaRegionPage();
        return fragment;
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_china_region, container, false);
        unbinder = ButterKnife.bind(this, view);
        selectRegionAdapter = new SelectRegionAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(selectRegionAdapter);
        selectRegionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (selectRegionAdapter.getItem(position).getType() == RegionItem.TYPE_DATA) {
                    //LocationUtil.setCurrentUserSelectRegion(new RegionData(selectRegionAdapter.getItem(position).getName(), selectRegionAdapter.getItem(position).getFullName()));
                    EventBus.getDefault().post(new EventPickRegion(new RegionData(selectRegionAdapter.getItem(position).getName(), selectRegionAdapter.getItem(position).getFullName(), selectRegionAdapter.getItem(position).getId())));
                    getActivity().finish();
                    getActivity().overridePendingTransition(R.anim.activity_still, R.anim.activity_slide_out_bottom);
                }
            }
        });
        recyclerView.addItemDecoration(new PinnedHeaderItemDecoration.Builder(RegionItem.TYPE_INDEX)
                .enableDivider(false)
                .setHeaderClickListener(null)
                .create());
        selectionRegionTagArray = getContext().getResources().getStringArray(R.array.SelectRegionTag);
        sideBar.setIndexItems(selectionRegionTagArray);


        currentRegionHeaderAdapter = new SelectRegionHeaderAdapter();
        currentRegionHeaderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HeaderRegionItem headerRegionItem = (HeaderRegionItem) adapter.getItem(position);
                switch (headerRegionItem.getType()) {
                    case HeaderRegionItem.TYPE_FAILED: {
                        LocationService.startLocation(view.getContext());
                        headerRegionItem.setType(HeaderRegionItem.TYPE_LOCALIZING);
                        currentRegionHeaderAdapter.notifyDataSetChanged();
                        historyRegionHeaderAdapter.notifyDataSetChanged();
                        break;
                    }
                    case HeaderRegionItem.TYPE_LOCALIZING:
                        break;
                    case HeaderRegionItem.TYPE_SUCCEED:
                        //LocationUtil.setCurrentUserSelectRegion(new RegionData(headerRegionItem.getName(), headerRegionItem.getFullName()));
                        EventBus.getDefault().post(new EventPickRegion(new RegionData(headerRegionItem.getName(), headerRegionItem.getFullName(), headerRegionItem.getId())));
                        getActivity().finish();
                        getActivity().overridePendingTransition(R.anim.activity_still, R.anim.activity_slide_out_bottom);
                        break;
                }
            }
        });
        historyRegionHeaderAdapter = new SelectRegionHeaderAdapter();
        historyRegionHeaderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HeaderRegionItem headerRegionItem = (HeaderRegionItem) adapter.getItem(position);
                switch (headerRegionItem.getType()) {
                    case HeaderRegionItem.TYPE_FAILED: {
                        LocationService.startLocation(view.getContext());
                        headerRegionItem.setType(HeaderRegionItem.TYPE_LOCALIZING);
                        currentRegionHeaderAdapter.notifyDataSetChanged();
                        historyRegionHeaderAdapter.notifyDataSetChanged();
                        break;
                    }
                    case HeaderRegionItem.TYPE_LOCALIZING:
                        break;
                    case HeaderRegionItem.TYPE_SUCCEED:
                        //LocationUtil.setCurrentUserSelectRegion(new RegionData(headerRegionItem.getName(), headerRegionItem.getFullName()));
                        EventBus.getDefault().post(new EventPickRegion(new RegionData(headerRegionItem.getName(), headerRegionItem.getFullName(), headerRegionItem.getId())));
                        getActivity().finish();
                        getActivity().overridePendingTransition(R.anim.activity_still, R.anim.activity_slide_out_bottom);
                        break;
                }
            }
        });
        hotRegionHeaderAdapter = new SelectRegionHeaderAdapter();
        hotRegionHeaderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HeaderRegionItem headerRegionItem = (HeaderRegionItem) adapter.getItem(position);
                switch (headerRegionItem.getType()) {
                    case HeaderRegionItem.TYPE_FAILED: {
                        LocationService.startLocation(view.getContext());
                        headerRegionItem.setType(HeaderRegionItem.TYPE_LOCALIZING);
                        currentRegionHeaderAdapter.notifyDataSetChanged();
                        historyRegionHeaderAdapter.notifyDataSetChanged();
                        break;
                    }
                    case HeaderRegionItem.TYPE_LOCALIZING:
                        break;
                    case HeaderRegionItem.TYPE_SUCCEED:
                        // LocationUtil.setCurrentUserSelectRegion(new RegionData(headerRegionItem.getName(), headerRegionItem.getFullName()));
                        EventBus.getDefault().post(new EventPickRegion(new RegionData(headerRegionItem.getName(), headerRegionItem.getFullName(), headerRegionItem.getId())));
                        getActivity().finish();
                        getActivity().overridePendingTransition(R.anim.activity_still, R.anim.activity_slide_out_bottom);
                        break;
                }
            }
        });

        currentRegionHeader = LayoutInflater.from(getContext()).inflate(R.layout.select_region_header_current, (ViewGroup) recyclerView.getParent(), false);
        historyRegionHeader = LayoutInflater.from(getContext()).inflate(R.layout.select_region_header, (ViewGroup) recyclerView.getParent(), false);
        hotRegionHeader = LayoutInflater.from(getContext()).inflate(R.layout.select_region_header, (ViewGroup) recyclerView.getParent(), false);

        configHeader(currentRegionHeader, R.string.current_region, currentRegionHeaderAdapter, currentRegionItemList);
        configHeader(historyRegionHeader, R.string.history_region, historyRegionHeaderAdapter, historyRegionItemList);
        configHeader(hotRegionHeader, R.string.hot_region, hotRegionHeaderAdapter, hotRegionItemList);
        sideBar.setOnSelectIndexItemListener(new WaveSideBar.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(String index) {
                Integer position = tagPositionMap.get(index);
                if (position != null) {
                    ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, UIHelper.dip2px(getContext(), 70));
                }
            }
        });

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = "";
                try {
                    action = intent.getAction();
                } catch (Exception e) {

                }
                switch (action) {
                    case LocationService.ACTION_LOCATION_FINISH: {
                        LocationData locationData = null;
                        try {
                            locationData = intent.getParcelableExtra(LocationService.EXTRA_LOCATION_DATA);
                        } catch (Exception e) {

                        }
                        currentRegionItemList.clear();
                        HeaderRegionItem currentHeaderRegionItem = new HeaderRegionItem();
                        if (locationData != null && locationData.isSuccess()) {
                            currentHeaderRegionItem.setName(locationData.getCity());
                            currentHeaderRegionItem.setFullName(locationData.getCountry() + " " + locationData.getProvince() + " " + locationData.getCity());
                            currentHeaderRegionItem.setId(DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity()));
                            currentHeaderRegionItem.setType(HeaderRegionItem.TYPE_SUCCEED);
                        } else {
                            currentHeaderRegionItem.setType(HeaderRegionItem.TYPE_FAILED);
                        }
                        currentRegionItemList.add(currentHeaderRegionItem);
                        List<HeaderRegionItem> tempHistoryRegionItemList = LocationUtil.getCurrentUserHistoryRegion();
                        historyRegionItemList.clear();
                        if (tempHistoryRegionItemList.isEmpty()) {
                            historyRegionItemList.add(currentHeaderRegionItem);
                        } else {
                            historyRegionItemList.addAll(tempHistoryRegionItemList);
                        }
                        prepareData();
                        break;
                    }
                    default:
                        break;
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocationService.ACTION_LOCATION_FINISH);
        getContext().registerReceiver(receiver, intentFilter);
        Toast.makeText(getContext(), R.string.loading, Toast.LENGTH_SHORT).show();
        LocationService.startLocation(getContext());
        return view;
    }


    public void prepareData() {
        new AsyncTask<Object, Object, Object>() {

            @Override
            protected Object doInBackground(Object[] params) {
                List<RegionItem> tempRegionItemList = DummyDataUtil.getChinaRegionData();
                if (tempRegionItemList != null) {
                    regionItemList = tempRegionItemList;
                }
                try {
                    Response<ResponseBody> response = ApiManager.getService().hotCity(SetupUtil.CHANNEL_ALL, SetupUtil.GROUP_TYPE_CITY).execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    List<TagPopular> tagPopularList = JSON.parseArray(json, TagPopular.class);
                    hotRegionItemList.clear();
                    int upLimit = Math.min(LocationUtil.MAX_HOT_REGION_NUM, tagPopularList.size());
                    for (int i = 0; i < upLimit; ++i) {
                        hotRegionItemList.add(new HeaderRegionItem(tagPopularList.get(i).getName(), tagPopularList.get(i).getSubGroupName() + " " + tagPopularList.get(i).getName(), tagPopularList.get(i).getId()));
                    }

                } catch (Exception e) {
                    //  ToastX.show(e.getMessage());
                }
                return null;
            }

            @Override
            protected void onPostExecute(Object o) {
                updateView();
            }
        }.execute();
    }


    public void updateView() {
        if (currentRegionItemList.isEmpty()) {
            currentRegionHeader.setVisibility(View.GONE);
        } else {
            currentRegionHeaderAdapter.notifyDataSetChanged();
            currentRegionHeader.setVisibility(View.VISIBLE);
        }

        if (historyRegionItemList.isEmpty()) {
            historyRegionHeader.setVisibility(View.GONE);
        } else {
            historyRegionHeaderAdapter.notifyDataSetChanged();
            historyRegionHeader.setVisibility(View.VISIBLE);
        }

        if (hotRegionItemList.isEmpty()) {
            hotRegionHeader.setVisibility(View.GONE);
        } else {
            hotRegionHeaderAdapter.notifyDataSetChanged();
            hotRegionHeader.setVisibility(View.VISIBLE);
        }


        selectRegionAdapter.setNewData(regionItemList);
        buildTagPositionMap();
    }


    public void buildTagPositionMap() {
        tagPositionMap.clear();
        int position = 0;
        tagPositionMap.put(selectionRegionTagArray[0], 0);
        position++;
        tagPositionMap.put(selectionRegionTagArray[1], 0);
        position++;
        tagPositionMap.put(selectionRegionTagArray[2], 0);
        position++;
        for (RegionItem regionItem : regionItemList) {
            if (regionItem.getItemType() == RegionItem.TYPE_INDEX) {
                tagPositionMap.put(regionItem.getIndex(), position);
            }
            position++;
        }
    }


    private void configHeader(View header, int titleResId, BaseQuickAdapter adapter, List<HeaderRegionItem> headerRegionItemList) {
        RecyclerView headerRecyclerView = (RecyclerView) header.findViewById(R.id.headerRv);
        headerRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        headerRecyclerView.setAdapter(adapter);
        adapter.setNewData(headerRegionItemList);
        TextView titleTv = (TextView) header.findViewById(R.id.titleTv);
        titleTv.setText(titleResId);
        header.setVisibility(View.GONE);
        selectRegionAdapter.addHeaderView(header);

    }


    @Override
    public void onDestroyView() {
        try {
            getContext().unregisterReceiver(receiver);
        } catch (Exception e) {
        }
        super.onDestroyView();
        unbinder.unbind();
    }


}
